
package com.scalar.chiptrack;

import java.util.Date;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.FunctionAccess;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;


public final class LoginAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {

        User user = null;
        HttpSession session = request.getSession();


        user = (User) session.getAttribute (SessionKeys.USER_KEY);
        if (user != null)
        {
            if ( user.getUserType() == Constants.USER_TYPE_CHIPTRAC )
            {
                return (new ActionForward (ConfigManager.getIndexPageByGroupName (user.getGroupName())));
            }
            else
            {
                return (new ActionForward("/jsp/admin/extUser.jsp"));
            }
        }

        LoginForm loginForm = (LoginForm) form;
        String userId = loginForm.getUserId();
        String password = loginForm.getPassword();

        LinkedHashMap errors = new LinkedHashMap();
        if ((userId == null) || (userId.trim().length() == 0)) {
            errors.put ("User Name", "User ID required");
        }
        if ((password == null) || (password.length() == 0)) {
            errors.put ("Password", "Password required");
        }
        if (errors.isEmpty() == false) {
            request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
            return (mapping.findForward ("failure"));
        }

        //System.out.println ("User ID = " + userId + ", Password = " + password);

        String returnPath = ConfigManager.getDefaultLoginPage();

        try {
            // load user from database (includes password verification
            user = UserDAO.loadUser (userId, password);

            // if its not null, add the user object to session
            if (user != null) {
                ConfigManager.setCurrentUserEmail (user.getEmail());

                //Added by rohan on June 8th 2004 for removing the permissions for Sales order screens which are not needed
                //Checking if the integration type is Epicore
                if( Constants.SALES_INTEGRATION_TYPE_EPICORE.equalsIgnoreCase( ConfigManager.getSalesIntegrationType() ) )
                {
                    //Integration type is Epicore
                    removeSOScreensPermissionsForEpicoreIntegration( user );
                }

                session.setAttribute (SessionKeys.USER_KEY, user);


                System.out.println (userId + " has been logged in -- from " + request.getRemoteHost() + " -- on " + new Date (System.currentTimeMillis()));

                returnPath = (String) session.getAttribute (SessionKeys.SOURCE_PAGE_KEY);
                session.removeAttribute (SessionKeys.SOURCE_PAGE_KEY);

                if (returnPath == null)
                {
                    if ( user.getUserType() == Constants.USER_TYPE_CHIPTRAC )
                    {
                        returnPath = ConfigManager.getIndexPageByGroupName (user.getGroupName());
                    }
                    else
                    {
                        returnPath = "/jsp/admin/extUser.jsp";
                    }
                }
            }
        }
        catch (ScalarException se) {
            String error = "Internal Server Error";
            String exceptionMessage = se.getRootCause().getMessage();

            if (exceptionMessage.indexOf("Invalid password") != -1) {
                error = "Invalid Password";
            }
            else if (exceptionMessage.indexOf("Invalid user id") != -1) {
                error = "Invalid User ID";
            }

            errors = new LinkedHashMap();
            errors.put (error, "Login Failed");
            request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        }

        ActionForward forward = new ActionForward (returnPath);
        return (forward);
    }

    //Added by Rohan on June 8th 2004
    /**
     * This method will remove the permissions for the Sales Order screens which
     * are not needed when sales orders is integrated with Epicore
     *
     * @param user
     */
    public void removeSOScreensPermissionsForEpicoreIntegration( User user )
    {
        if( user != null )
        {
            user.getFunctionAccessMap().put( Functionality.SALES_NEW_SALES_ORDER.toLowerCase(), new FunctionAccess() );
            user.getFunctionAccessMap().put( Functionality.SALES_MISSED_ORDER.toLowerCase(), new FunctionAccess() );
            user.getFunctionAccessMap().put( Functionality.SALES_CHANGE_ORDER.toLowerCase(), new FunctionAccess() );
            user.getFunctionAccessMap().put( Functionality.SALES_CANCELLED_ORDER.toLowerCase(), new FunctionAccess() );
            user.getFunctionAccessMap().put( Functionality.SALES_HOLDS_RELEASE.toLowerCase(), new FunctionAccess() );
            user.getFunctionAccessMap().put( Functionality.SALES_HOLDS_RELEASES.toLowerCase(), new FunctionAccess() );
        }
    }
}